package com.tanhua.sso.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.vo.PicUploadResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Service
public class UserInfoService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private FaceEngineService faceEngineService;

    @Autowired
    private PicUploadService picUploadService;

    /**
     * 完善个人信息
     *
     * @param param
     * @param token
     * @return
     */
    public Boolean saveUserInfo(Map<String, String> param, String token) {
        //校验tock是否正确
        User user = this.userService.queryUserByToken(token);
        //判断用户返回信息
        if (user == null) {
            return false;
        }
        //token正确,就往里面添加数据
        UserInfo userInfo = new UserInfo();
        //equalsIgnoreCase与字符串进行比较的对象
        userInfo.setUserId(user.getId());
        userInfo.setSex(StringUtils.equalsIgnoreCase(param.get("gender"), "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setNickName(param.get("nickname"));
        userInfo.setBirthday(param.get("birthday"));
        userInfo.setCity(param.get("city"));
        return this.userInfoMapper.insert(userInfo) == 1;

    }

    public Boolean saveUserLogo(MultipartFile file, String token) {

        User user = this.userService.queryUserByToken(token);
        //返回数据为空
        if (user == null) {
            //，token错误
            return false;
        }

        try {
            //获取到这个图片
            boolean b = this.faceEngineService.checkIsPortrait(file.getBytes());
            //判断不是人脸,，如果不是人像就返回false
            if (!b) {
                return false;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        //直接上传阿里云oss
        PicUploadResult result = this.picUploadService.upload(file);
        //判断图片是否为空
        if (StringUtils.isEmpty(result.getName())) {
            //上传失败
            return false;
        }

        //把头像保存到个人信息中
        UserInfo userInfo = new UserInfo();
        userInfo.setLogo(result.getName());

        //创建条件构造器，修改头像
        QueryWrapper<UserInfo> querWrapper = new QueryWrapper<>();
        querWrapper.eq("user_id", user.getId());
        return this.userInfoMapper.update(userInfo, querWrapper) == 1;

    }
}
